<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区域" prop="areaid">
        <el-select v-model="queryParams.areaid" filterable placeholder="请选择区域" clearable size="small">
          <el-option
            v-for="region in regionList"
            :key="region.areaid"
            :label="region.city+'-'+region.county+'-'+region.town+'-'+region.village"
            :value="region.areaid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="停用" prop="closed">
        <el-select v-model="queryParams.closed" placeholder="请选择停用" clearable size="small">
          <el-option
            v-for="dict in dict.type.is_closed"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:guest:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:guest:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:guest:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-user"
          size="mini"
          :disabled="multiple"
          @click="handleBatchGenerateUser"
          v-hasPermi="['system:guest:binduser']"
        >生成用户
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-user"
          size="mini"
          @click="handleBatchGenerateUserAll"
          v-hasPermi="['system:guest:binduser']"
        >一键生成用户
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:guest:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:guest:import']"
        >导入
        </el-button>
      </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="guestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="编码" prop="code"/>
      <el-table-column label="客户" prop="name"/>
      <el-table-column label="区域" prop="areaid">
        <template slot-scope="scope">
          {{ regionMatching(scope.row.areaid) }}
        </template>
      </el-table-column>
      <el-table-column label="业务员" prop="empid">
        <template slot-scope="scope">
          {{ employeeMatching(scope.row.empid) }}
        </template>
      </el-table-column>
      <el-table-column label="联系人" prop="contractor"/>
      <el-table-column label="联系人手机" prop="phone"/>
      <el-table-column label="地址" prop="address"/>
      <el-table-column label="联系人固话" prop="tel"/>
      <el-table-column label="客户链接" prop="url"/>
      <el-table-column label="司机" prop="driverid">
        <template slot-scope="scope">
          {{ driverMatching(scope.row.driverid) }}
        </template>
      </el-table-column>
      <el-table-column label="授信额度" prop="creditamount"/>
      <el-table-column label="账户余额" prop="amount"/>
      <el-table-column label="登录用户" prop="userName"/>
      <el-table-column label="停用" prop="closed">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.is_closed" :value="scope.row.closed"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:guest:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:guest:remove']"
          >删除
          </el-button>
          <el-button v-if="scope.row.userid==null"
                     size="mini"
                     type="text"
                     icon="el-icon-user"
                     @click="handleBindUser(scope.row)"
                     v-hasPermi="['system:guest:binduser']"
          >绑定用户
          </el-button>
          <el-button v-if="scope.row.userid==null"
                     size="mini"
                     type="text"
                     icon="el-icon-user"
                     @click="handleGenerateUser(scope.row)"
                     v-hasPermi="['system:guest:generateuser']"
          >生成用户
          </el-button>
          <el-button v-if="scope.row.userid!=null"
                     size="mini"
                     type="text"
                     icon="el-icon-user"
                     @click="handleUnBindUser(scope.row)"
                     v-hasPermi="['system:guest:binduser']"
          >解绑用户
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item label="客户" prop="name">
              <el-input v-model="form.name" placeholder="请输入客户"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="区域" prop="areaid">
              <el-select v-model="form.areaid" filterable placeholder="请选择区域" clearable size="small">
                <el-option
                  v-for="region in regionList"
                  :key="region.areaid"
                  :label="region.city+'-'+region.county+'-'+region.town+'-'+region.village"
                  :value="region.areaid"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item label="业务员" prop="empid">
              <el-select v-model="form.empid" filterable placeholder="请选择业务员" clearable size="small">
                <el-option
                  v-for="employee in employeeList"
                  :key="employee.empid"
                  :label="employee.name"
                  :value="employee.empid"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contractor">
              <el-input v-model="form.contractor" placeholder="请输入联系人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item label="联系人手机" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系人手机"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item label="联系人固话" prop="tel">
              <el-input v-model="form.tel" placeholder="请输入联系人固话"/>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">

            <el-form-item label="客户链接" prop="url">
              <el-input v-model="form.url" placeholder="请输入客户链接"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="司机" prop="driverid">
              <el-select v-model="form.driverid" filterable placeholder="请选择司机" clearable size="small">
                <el-option
                  v-for="driver in driverList"
                  :key="driver.empid"
                  :label="driver.name"
                  :value="driver.empid"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="授信额度" prop="creditamount">
              <el-input v-model="form.creditamount" placeholder="请输入授信额度"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="停用" prop="closed">
              <el-select v-model="form.closed" placeholder="请选择停用">
                <el-option
                  v-for="dict in dict.type.is_closed"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改客户对话框 -->
    <el-dialog title="绑定用户信息" :visible.sync="bindOpen" width="300px" append-to-body>
      <el-form ref="form" :model="bindform" label-width="100px">
        <el-select v-model="bindform.userid" filterable placeholder="请选择绑定的用户" clearable size="small">
          <el-option
            v-for="user in bindUserList"
            :key="user.userId"
            :label="user.nickName+'-'+user.userName"
            :value="user.userId"
          />
        </el-select>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="bindUser">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="批量绑定用户提示" :visible.sync="batchOpen" width="500px" append-to-body>
      <div>
        <p v-for="(batchMsg,i) in batchMsgArr">{{ i + 1 }}：{{ batchMsg.msg }}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelBatch">确 定</el-button>
      </div>
    </el-dialog>


    <!-- 客户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGuest,
  getGuest,
  delGuest,
  addGuest,
  updateGuest,
  bindUserList,
  bindUser,
  generateUser, batchGenerateUser, batchGenerateUserAll
} from "@/api/system/guest";
import {listRegionAll} from "@/api/system/region";
import {listDriverAll, listSalesmanAll} from "@/api/system/employee";
import {getToken} from "@/utils/auth";

export default {
  name: "Guest",
  dicts: ['is_closed'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      guestList: [],
      //司机列表
      driverList: [],
      //员工列表
      employeeList: [],
      //区域列表
      regionList: [],
      //绑定用户列表
      bindUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否弹出绑定用户层
      bindOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        areaid: null,
        empid: null,
        contractor: null,
        phone: null,
        address: null,
        tel: null,
        url: null,
        driverid: null,
        creditamount: null,
        amount: null,
        closed: null,
      },
      // 表单参数
      form: {},
      bindform: {},
      // 表单校验
      rules: {
        code: [
          {required: true, message: "编码不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "客户不能为空", trigger: "blur"}
        ],
        createTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ],
        createBy: [
          {required: true, message: "创建人不能为空", trigger: "blur"}
        ],
        phone: [
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      },
      batchMsgArr: [],
      batchOpen: false,
      // 货品导入参数
      upload: {
        // 是否显示弹出层（货品）
        open: false,
        // 弹出层标题（货品）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/guest/importData"
      },
    };
  },
  created() {
    this.getList();
    this.getRegionList();
    this.getDriverList();

  },
  methods: {
    getbindUserList() {

      bindUserList().then(response => {
        this.bindUserList = response.data;
      })
    },
    getRegionList() {
      listRegionAll().then(response => {
        this.regionList = response.data;
      });
    },
    getDriverList() {
      listDriverAll().then(response => {
        this.driverList = response.data;
        this.getSalesmanList();
      });
    },
    getSalesmanList() {
      listSalesmanAll().then(response => {
        this.employeeList = response.data;
      });
    },
    regionMatching(areaid) {
      let name = "-";
      this.regionList.map(item => {
        if (areaid == item.areaid) {
          name = item.city + '-' + item.county + '-' + item.town + '-' + item.village;
          return
        }
      })
      return name;
    },
    employeeMatching(employeeId) {
      let name = "-";
      this.employeeList.map(item => {
        if (employeeId == item.empid) {
          name = item.name;
          return
        }
      })
      return name;
    },

    driverMatching(employeeId) {
      let name = "-";
      this.driverList.map(item => {
        if (employeeId == item.empid) {
          name = item.name;
          return
        }
      })
      return name;
    },
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      listGuest(this.queryParams).then(response => {
        this.guestList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.bindOpen = false;
      this.reset();
    },
    cancelBatch() {
      this.batchOpen = false;
    },
    // 表单重置
    reset() {
      this.form = {
        gid: null,
        code: null,
        name: null,
        areaid: null,
        empid: null,
        contractor: null,
        phone: null,
        address: null,
        tel: null,
        url: null,
        driverid: null,
        creditamount: null,
        amount: null,
        remark: null,
        closed: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      };
      this.bindform = {
        gid: null,
        userid: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.gid)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const gid = row.gid || this.ids
      getGuest(gid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.gid != null) {
            updateGuest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGuest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /**绑定用户**/
    bindUser() {
      if (!this.bindform.userid) {
        this.$modal.msgWarning("请选择本地的用户");
        return
      }
      if (!this.bindform.gid) {
        this.$modal.msgWarning("提交失败");
        return
      }
      bindUser(this.bindform).then(response => {
        let data = response.data
        if (data.code == 1) {
          this.$modal.msgSuccess(data.msg);
        } else {
          this.$modal.msgWarning(data.msg);
        }
        this.getList();
      }).catch(() => {
      });
    },
    /**解绑定用户**/
    unBindUser() {
      if (!this.bindform.gid) {
        this.$modal.msgWarning("提交失败");
        return
      }
      bindUser(this.bindform).then(response => {
        let data = response.data
        if (data.code == 1) {
          this.$modal.msgSuccess(data.msg);
        } else {
          this.$modal.msgWarning(data.msg);
        }
        this.getList();
      }).catch(() => {
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const gids = row.gid || this.ids;
      this.$modal.confirm('是否确认删除客户编号为"' + gids + '"的数据项？').then(function () {
        return delGuest(gids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 绑定用户按钮操作 */
    handleBindUser(row) {
      this.bindform = {
        gid: row.gid
      }
      this.getbindUserList();
      this.bindOpen = true;
    },
    /** 创建用户按钮操作 */
    handleGenerateUser(row) {
      let generateForm = {
        gid: row.gid
      }
      generateUser(generateForm).then(response => {
        let data = response.data
        if (data.code == 1) {
          this.$modal.msgSuccess(data.msg);
        } else {
          this.$modal.msgWarning(data.msg);
        }
        this.getList();
      }).catch(() => {
      });
    },
    handleUnBindUser(row) {
      this.$confirm('是否解绑用户信息？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '是',
        cancelButtonText: '否'
      })
        .then(() => {
          this.bindform = {
            gid: row.gid
          }
          this.unBindUser()
        })
    },
    handleBatchGenerateUser() {
      const gids = this.ids;
      this.batchMsgArr = [];
      this.$modal.loading("请求中");
      this.$modal.confirm('是否确认生成账号？').then(function () {
        return batchGenerateUser(gids);
      }).then(response => {
        this.batchOpen = true;
        this.batchMsgArr = response.data;
        this.$modal.closeLoading();
        this.getList();
      }).catch(() => {
        this.$modal.closeLoading();
      });
    },
    handleBatchGenerateUserAll() {
      this.batchMsgArr = [];
      this.$modal.loading("请求中");
      this.$modal.confirm('是否确认生成账号？').then(function () {
        return batchGenerateUserAll();
      }).then(response => {
        this.batchOpen = true;
        this.batchMsgArr = response.data;
        this.$modal.closeLoading();
        this.getList();
      }).catch(() => {
        this.$modal.closeLoading();
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/guest/export', {
        ...this.queryParams
      }, `guest_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "客户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/guest/importTemplate', {}, `客户导入模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
